package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    //feign同步调用
    //@Autowired
    //private IArticleClient articleClient;


    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {

        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Page page = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus()!=null){
            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }

        if (dto.getChannelId()!=null){
            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        if (dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null) {
            lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }

        if (StringUtils.isNotBlank(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }

        lambdaQueryWrapper.eq(WmNews::getUserId,user.getId());

        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);
        page = page(page,lambdaQueryWrapper);
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }



    /**
     * 发布修改文章或保存为草稿
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {

        //0.条件判断
        if(dto == null || dto.getContent() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1.保存或修改文章

        WmNews wmNews = new WmNews();
        //属性拷贝 属性名词和类型相同才能拷贝
        BeanUtils.copyProperties(dto,wmNews);
        //封面图片  list---> string
        if(dto.getImages() != null && dto.getImages().size() > 0){
            //[1dddfsd.jpg,sdlfjldk.jpg]-->   1dddfsd.jpg,sdlfjldk.jpg
            String imageStr = org.apache.commons.lang3.StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imageStr);
        }
        //如果当前封面类型为自动 -1
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }

        saveOrUpdateWmNews(wmNews);

        //2.判断是否为草稿  如果为草稿结束当前方法
        if(dto.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //3.不是草稿，保存文章内容图片与素材的关系
        //获取到文章内容中的图片信息
        List<String> materials =  ectractUrlInfo(dto.getContent());
        saveRelativeInfoForContent(materials,wmNews.getId());

        //4.不是草稿，保存文章封面图片与素材的关系，如果当前布局是自动，需要匹配封面图片
        saveRelativeInfoForCover(dto,wmNews,materials);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 第一个功能：如果当前封面类型为自动，则设置封面类型的数据
     * 匹配规则：
     * 1，如果内容图片大于等于1，小于3  单图  type 1
     * 2，如果内容图片大于等于3  多图  type 3
     * 3，如果内容没有图片，无图  type 0
     *
     * 第二个功能：保存封面图片与素材的关系
     * @param dto
     * @param wmNews
     * @param materials
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {

        List<String> images = dto.getImages();

        //如果当前封面类型为自动，则设置封面类型的数据
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            //多图
            if(materials.size() >= 3){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            }else if(materials.size() >= 1 && materials.size() < 3){
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            }else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            //修改文章
            if(images != null && images.size() > 0){
                wmNews.setImages(org.apache.commons.lang3.StringUtils.join(images,","));
            }
            updateById(wmNews);
        }
        if(images != null && images.size() > 0){
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }

    }


    /**
     * 处理文章内容图片与素材的关系
     * @param materials
     * @param newsId
     */
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials,newsId,WemediaConstants.WM_CONTENT_REFERENCE);
    }

    /**
     * 保存文章图片与素材的关系到数据库中
     * @param materials
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        if(materials!=null && !materials.isEmpty()){
            //通过图片的url查询素材的id
            List<WmMaterial> dbMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));

            //判断素材是否有效
            if(dbMaterials==null || dbMaterials.size() == 0){
                //手动抛出异常   第一个功能：能够提示调用者素材失效了，第二个功能，进行数据的回滚
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }

            if(materials.size() != dbMaterials.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }

            List<Integer> idList = dbMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());

            //批量保存
            wmNewsMaterialMapper.saveRelations(idList,newsId,type);
        }

    }


    /**
     * 提取文章内容中的图片信息
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> materials = new ArrayList<>();

        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if(map.get("type").equals("image")){
                String imgUrl = (String) map.get("value");
                materials.add(imgUrl);
            }
        }

        return materials;
    }


    /**
     * 保存或修改文章
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //补全属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short)1);//默认上架

        if(wmNews.getId() == null){
            //保存
            save(wmNews);
        }else {
            //修改
            //删除文章图片与素材的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }

    }


    /**
     * 功能描述: 异步进行文章审核业务-文章提交审核后进行自动文章审核
     * @param id
     * @return : void
     */
    @Override
    @Async
    public void autoScanWmNews(Integer id) throws Exception {
        //1.校验参数
        if(id == null){
            return;
        }
        //2.根据自媒体文章ID获取自媒体文章内容
        WmNews wmNews = wmNewsMapper.selectById(id);
        if(wmNews == null){
            return;
        }
        //3.内容不为空，进行文字内容审核：标题、标签、文章内容，审核失败直接修改文章状态、给出失败原因，返回。
        //3.1 提取文章中文本内容信息
        String title = wmNews.getTitle();
        String tag = wmNews.getLabels();
        String content = wmNews.getContent();
        List<String> contents = contents(content);
        contents.add(title);
        contents.add(tag);
        String contentResult = org.apache.commons.lang3.StringUtils.join(contents, ",");
        Map map = greenTextScan.greeTextScan(contentResult);
        String suggestion = (String)map.get("suggestion");
        if("block".equals(suggestion)){
            wmNews.setStatus((short)2);
            String label = (String)map.get("label");
            wmNews.setReason("文章内容存在违规内容："+label);
            wmNewsMapper.updateById(wmNews);
            return;
        }
        if("review".equals(suggestion)){
            wmNews.setStatus((short)3);
            String label = (String)map.get("label");
            wmNews.setReason("文章内容存在可疑内容："+label);
            wmNewsMapper.updateById(wmNews);
            return;
        }
        //4.图片内容不为空（封面图片和内容图片进行整体的去重处理-省钱），进行图片审核：封面图片、内容图片，审核失败直接修改文章状态、给出失败原因返回。
        //4.1获取内容中图片
        Set<String> contentImageList = getContentImageList(content);
        //4.2获取封面中图片
        String images = wmNews.getImages();
        String[] coverImageList = images.split(",");
        //4.3内容图片和封面图片合并
        Collections.addAll(contentImageList, coverImageList);
        //4.4根据URL地址，下载图片，获取图片的字节数组
        List<byte[]> imgList = new ArrayList<>();
        for (String imgUrl : contentImageList) {
            byte[] bytes = fileStorageService.downLoadFile(imgUrl);
            imgList.add(bytes);
        }
        Map imgResultMap = greenImageScan.imageScan(imgList);
        String imgSuggestion = (String)imgResultMap.get("suggestion");
        if("block".equals(imgSuggestion)){
            wmNews.setStatus((short)2);
            String label = (String)map.get("label");
            wmNews.setReason("文章中图片存在违规内容："+label);
            wmNewsMapper.updateById(wmNews);
            return;
        }
        if("review".equals(imgSuggestion)){
            wmNews.setStatus((short)3);
            String label = (String)map.get("label");
            wmNews.setReason("文章中图片存在可疑内容："+label);
            wmNewsMapper.updateById(wmNews);
            return;
        }
        //5.图片中文字审核：提取图片中文字，进行审核，，审核失败直接修改文章状态、给出失败原因，返回。--TODO
        //6.修改文章状态、调用APP端文章保存接口，获取app端文章ID --TODO
        Date currentDate = new Date();
        short status = 8;
        if(wmNews.getPublishTime().getTime() <= currentDate.getTime()){//发布时间小于等于当前时间，发布时间到了或过了
            status = 9;
        }
        wmNews.setStatus(status);
        //ResponseResult result = articleClient.saveArticle();---
        wmNewsMapper.updateById(wmNews);
        return;
    }

    /**
     * 功能描述: 封装WmNews对象
     * @param dto
     * @param wmNews
     * @return : com.heima.model.wemedia.pojos.WmNews
     */
    public WmNews completion(WmNewsDto dto,WmNews wmNews){
        BeanUtils.copyProperties(dto,wmNews);
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setStatus((short)0);
        wmNews.setEnable((short)1);
        List<String> imageList = dto.getImages();
        if(dto.getType() == -1){//类型为自动
            short type = 0;
            //从内容中提取图片信息
            Set<String> imgs = new HashSet<>();
            String content = dto.getContent();
            if(org.apache.commons.lang3.StringUtils.isNotBlank(content)){
                List<WmNewsContent> contentList = JSONObject.parseArray(content, WmNewsContent.class);
                for (WmNewsContent wmNewsContent : contentList) {
                    if("image".equals(wmNewsContent.getType())){
                        imgs.add(wmNewsContent.getValue());
                        continue;
                    }
                }
            }
            int size = imgs.size();
            if(size < 1){
                type = 0;
            } else if (size>=3 ) {
                type = 3;
                imageList = imgs.stream().limit(3).collect(Collectors.toList());
            } else {
                type = 1;
                imageList = imgs.stream().limit(1).collect(Collectors.toList());
            }
            wmNews.setType(type);
        }
        wmNews.setImages(org.apache.commons.lang3.StringUtils.join(imageList,","));//现成方法
        return wmNews;
    }
    /**
     * 功能描述: 删除文章和素材关联关系
     * @param id 自媒体文章ID
     * @return : void
     */
    public void removeRelationship(Integer id){
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getNewsId,id);
        wmNewsMaterialMapper.delete(queryWrapper);
    }
    /**
     * 功能描述: 获取封面图片列表
     * @param dto 前端传递的请求参数
     * @return : java.util.List<java.lang.String>
     */
    public List<String> coverImages(WmNewsDto dto) {
        List<String> imageList = dto.getImages();
        if (dto.getType() == -1) {//类型为自动
            short type = 0;
            //从内容中提取图片信息
            String content = dto.getContent();
            Set<String> imgs = getContentImageList(content);
            int size = imgs.size();
            if (size < 1) {
                type = 0;
            } else if (size >= 3) {
                type = 3;
                imageList = imgs.stream().limit(3).collect(Collectors.toList());
            } else {
                type = 1;
                imageList = imgs.stream().limit(1).collect(Collectors.toList());
            }
        }
        return imageList;
    }
    /**
     * 功能描述: 获取文章内容中图片列表
     * @param content 文章内容的JsonArray字符串
     * @return : java.util.Set<java.lang.String>
     */
    public Set<String> getContentImageList(String content){
        //从内容中提取图片信息
        Set<String> imgs = new HashSet<>();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(content)) {
            List<WmNewsContent> contentList = JSONObject.parseArray(content, WmNewsContent.class);
            for (WmNewsContent wmNewsContent : contentList) {
                if ("image".equals(wmNewsContent.getType())) {
                    imgs.add(wmNewsContent.getValue());
                    continue;
                }
            }
        }
        return imgs;
    }
    /**
     * 功能描述: 根据素材的url地址列表，获取素材的id列表
     * @param dto
     * @return : java.util.List<java.lang.Integer>
     */
    public List<Integer> getMetarialIds(WmNewsDto dto){
        List<String> coverImages = coverImages(dto);
        if(coverImages == null || coverImages.size() ==0){
            return new ArrayList<>();
        }
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WmMaterial::getUrl,coverImages);
        queryWrapper.select(WmMaterial::getId);
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(queryWrapper);
        List<Integer> wmMaterialIds = wmMaterials.stream().map(wmMaterial -> wmMaterial.getId()).collect(Collectors.toList());
        return wmMaterialIds;
    }

    /**
     * 功能描述: 获取文章的所有文本内容
     * @param content 自媒体文章内容，JsonArray类型字符串 "[{},{},{}]"
     * @return : java.util.List<java.lang.String>
     */
    public List<String> contents(String content){
        List<String> contents = new ArrayList<>();
        List<WmNewsContent> contentList = JSON.parseArray(content, WmNewsContent.class);
        for (WmNewsContent wmNewsContent : contentList) {
            if("text".equals(wmNewsContent.getType())){
                contents.add(wmNewsContent.getValue());
            }
        }
        return contents;
    }


    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    /**
     * 文章的上下架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        //3.判断文章是否已发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前文章不是发布状态，不能上下架");
        }

        //4.修改文章enable
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable,dto.getEnable())
                    .eq(WmNews::getId,wmNews.getId()));
        }
        Map<String, String> map = new HashMap<>();
        map.put("enable", String.valueOf(dto.getEnable()));
        WmNews wmNews1 = wmNewsMapper.selectById(dto.getId());
        map.put("articleId", String.valueOf(wmNews1.getArticleId()));
        kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
